package com.jee.ssm.modules.guideScreen.timer;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jee.ssm.common.config.AiparkConfig;
import com.jee.ssm.common.socket.guideScreen.SocketHandle;
import com.jee.ssm.common.socket.guideScreen.SocketServer;
import com.jee.ssm.common.utils.HttpUtils;
import com.jee.ssm.common.utils.ImageWordUtils;
import com.jee.ssm.common.utils.SingUtils;
import com.jee.ssm.common.utils.TimeUtils;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.common.utils.hik.HikUtils;
import com.jee.ssm.model.GuideScreen;
import com.jee.ssm.model.ParkDepot;
import com.jee.ssm.model.ReservationRecord;
import com.jee.ssm.model.aipark.AiparkReceive;
import com.jee.ssm.model.hik.ChargeRecord;
import com.jee.ssm.model.hik.HikPage;
import com.jee.ssm.model.hik.receive.HikBill;
import com.jee.ssm.model.hik.receive.ParkDepotInfo;
import com.jee.ssm.model.hik.receive.VehicleRecord;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.modules.guideScreen.services.GuideScreenService;
import com.jee.ssm.modules.hikBill.services.HikBillService;
import com.jee.ssm.modules.parkDepot.services.ParkDepotService;
import com.jee.ssm.modules.reservationRecord.services.ReservationRecordService;

@Component
public class RefreshData {
	
	private Logger logger = Logger.getLogger(RefreshData.class);
	
	@Resource
	private GuideScreenService gss;
	
	@Resource
    private ParkDepotService parkDepotService;
	
	@Resource
    private HikBillService hikBillService;
	
	@Resource
	private ReservationRecordService rrs;

//	@Scheduled(cron = "0 */5 * * * ?")//5分钟处理一次
	public void listScreen() {
		logger.info("诱导屏刷新执行时间：" + UUIDFactory.getCurrentTime());
		List<GuideScreen> list = gss.listScreen();
		String timeDirectory = String.valueOf(System.currentTimeMillis());
		for(GuideScreen gs : list) {
			SocketHandle s = SocketServer.socketMap.get(gs.getNumber());
			if(s != null) {
				handleScreen(gs, timeDirectory);//路況
//				handleScreenWord(gs);//埽黑除惡
			} else {
				logger.info(gs.getName() + "不在线");
			}
		}
	}
	
	@Scheduled(cron = "0 */3 * * * ?")//3分钟处理一次
	public void editReservationRecord() {
		logger.info("修改预约状态执行时间：" + UUIDFactory.getCurrentTime());
		List<ReservationRecord> list = rrs.listReservationRecordWithStatus(new ReservationRecord(1));
		List<String> sl = new ArrayList<>();
		for(ReservationRecord rr : list) {
			if(rr.getParkTime().getTime() < System.currentTimeMillis()) {
				sl.add(rr.getId());
			}
		}
		if(sl.size() > 0) {
			try {
				rrs.editListStatus(sl);
			} catch (Exception e) {
				System.out.println("批量修改失败");
				e.printStackTrace();
			}
		}
	}
	
	@Scheduled(cron = "0 */1 * * * ?")//1分钟处理一次
	public void sendDataToAipark() {
		logger.info("上传互通平台数据执行时间：" + UUIDFactory.getCurrentTime());
		sendLeftPlotList();
		//过车记录
		sendRecord();
	}
	
	@Scheduled(cron = "0 0 2 * * ?")//每天凌晨两点执行
	public void editHikBillOneDayAgo() {
		logger.info("每天定时修改海康账单数据执行时间：" + UUIDFactory.getCurrentTime());
		editHikBill(-1, null);
	}
	
	@Scheduled(cron = "0 0 */1 * * ?")//每小时处理一次
	public void editHikBillOneHourAgo() {
		logger.info("每小时定时修改海康账单数据执行时间：" + UUIDFactory.getCurrentTime());
		editHikBill(null, -1);
	}
	
	//---------------------------以下为诱导屏刷新的工具类---------------------------------------------------------------------------------------
	
	
	
	private void handleScreen(GuideScreen gs, String timeDirectory) {
		//当前播放为文字时
//		if(gs.getType() == 0) {
			try {
				boolean clean = false;
				Integer number = gs.getPlayNumber();
                gs.setPlayFileUrl("/images/guide-screen/del/" + timeDirectory + "/" + gs.getName() + "_" + gs.getNumber() + "/");
				if(number == null) {
					clean = true;
					gs.setPlayNumber(1);

				} else if(number < 50) {
					gs.setPlayNumber(number + 1);
				} else {
					clean = true;
					gs.setPlayNumber(1);
				}
				String num = createNumberByPlayNumber(gs.getPlayNumber());
				createFileAndSave(gs, num, clean);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
//		} else if(gs.getType() == 1) {//当前播放为图片时
//			Integer number = gs.getPlayNumber();
//			String url = "/images/guide-screen/download-method/", fileName = "play051.lst", imageName = "downloadmethod.jpg";
//            WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
//            ServletContext servletContext = webApplicationContext.getServletContext();
//            String filePath = servletContext.getRealPath(url);
//			gs.setUpdateTime(new Date());
//			gs.setType(0);
//			gs.setPlayFileUrl(url);
//			gs.setPlayFileName(fileName);
//			gs.setImageName(imageName);
//			try {
//				gss.updateById(gs);
//			} catch (Exception e) {
//				e.printStackTrace();
//				logger.info("修改类型失败");
//
//			}
//			if(number == null || number == 1) {
//				sendToScreen(51, gs.getNumber(), filePath, fileName, imageName, false);
//			} else {
//				SocketHandle s = SocketServer.socketMap.get(gs.getNumber());
//				if(s != null) {
//					s.play(51);
//				}
//			}
//		}
		
	}
	
	private void createFileAndSave(GuideScreen gs, String num, boolean clean) {
		try {
			String imageName = gs.getNumber() + "_" + gs.getBaiduNumber() + "_" + num + ".jpg";
			String url = gs.getPlayFileUrl();
			
			WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
			ServletContext servletContext = webApplicationContext.getServletContext();
        	String filePath = servletContext.getRealPath(url);
        	File d = new File(filePath);
        	if(!d.exists() && !d.isDirectory()) {
				d.mkdirs();
			}
        	String fileName = "play" + num + ".lst";
        	File file = new File(filePath + fileName);
        	if(file.exists()){
        		file.delete();
        	}
        	file.createNewFile();
            //创建文件成功后，写入内容到文件里
            writeFileContent(filePath + fileName, "[all]\nitems=1\n[item1]\nparam=5000,255,255,1,0,1,1,0,1\nimg1=0,0," + imageName + ",0,192,160\nimgparam1=5000");

            Tip topLeft = HikUtils.getLeftPlot(gs.getParkTopNumber());
            String top = "0";
            if(topLeft.getSuccess()) {
            	top = topLeft.getMessage();
            }
            Tip bottomLeft = HikUtils.getLeftPlot(gs.getParkBottomNumber());
            String bottom = "0";
            if(bottomLeft.getSuccess()) {
            	bottom = bottomLeft.getMessage();
            }
            
        	getImage(filePath, imageName, gs.getBaiduNumber(), gs.getTopWord() + top, gs.getBottomWord() + bottom);
        	gs.setUpdateTime(new Date());
        	gs.setType(1);
        	gs.setPlayFileUrl(url);
        	gs.setPlayFileName(fileName);
        	gs.setImageName(imageName);
        	
            gss.updateById(gs);
            
            sendToScreen(gs.getPlayNumber(), gs.getNumber(), filePath, fileName, imageName, clean);
		} catch(Exception e) {
			
		}
	}
	
	private String createNumberByPlayNumber(Integer playNumber) {
		String number = "";
		if(playNumber > 0 && playNumber < 10) {
			number = "00" + playNumber;
		} else if(playNumber > 9 && playNumber < 100 ) {
			number = "0" + playNumber;
		} else {
			number = String.valueOf(playNumber);
		}
		return number;
	}
	
	private void getImage(String path, String name, String number, String top, String bottom) throws IOException {
		String fileName = number + ".jpg";
		File file = new File(path);
		if(!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
		saveToFile("http://jiaotong.baidu.com/guidingscreen/screen/image?id=" + number, path + fileName);
		File f = new File(path + fileName);
		BufferedImage img = ImageIO.read(new FileInputStream(f));
		int width = img.getWidth();
		int height1 = img.getHeight();
		
		BufferedImage wordImg1 = ImageWordUtils.getPictureByWord(top, width);
		BufferedImage wordImg2 = ImageWordUtils.getPictureByWord(bottom, width);
		int height2 = wordImg1.getHeight();
		int height3 = wordImg2.getHeight();
		
		BufferedImage tag = new BufferedImage(width, height1 + height2 + height3, BufferedImage.TYPE_INT_RGB);
		
		Graphics g = tag.createGraphics();
		g.drawImage(wordImg1, 0, 0, width, height2, null);
		g.drawImage(img, 0, height2, width, height1, null);
		g.drawImage(wordImg2, 0, height1 + height2, width , height3, null);
		
		String result = path + name;
		ImageIO.write(tag, "JPEG", new File(result));
	}
    
	private static void saveToFile(String destUrl, String path) {
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;
		int BUFFER_SIZE = 1024;
		byte[] buf = new byte[BUFFER_SIZE];
		int size = 0;
		try {
			url = new URL(destUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(path);
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassCastException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
				bis.close();
				httpUrl.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
     * 向文件中写入内容
     * @param filepath 文件路径与名称
     * @param newstr  写入的内容
     * @return
     * @throws IOException
     */
	private static boolean writeFileContent(String filepath,String newstr) throws IOException {
		Boolean bool = false;
        String filein = newstr+"\r\n";//新写入的行，换行
        String temp  = "";
        
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos  = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);//文件路径(包括文件名称)
            //将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            
            //文件原有内容
            while((temp =br.readLine())!=null){
                buffer.append(temp);
                // 行与行之间的分隔符 相当于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);
            
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //不要忘记关闭
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }
    
    private void sendToScreen(Integer n, String number, String url, String fileName, String imageName, boolean clean) {

		 SocketHandle s = SocketServer.socketMap.get(number);
		 if(s != null) {
			 if(clean) {
				 s.cleanAll();
			 }
			 try {
				 List<Byte> list = getFileInfo(url + imageName);
				 s.sendFileName(list.size(), imageName);
				 s.sendFile(list);
				 
				 List<Byte> playlist = getFileInfo(url + fileName);
				 s.sendFileName(playlist.size() + 100, fileName);
				 s.sendFile(playlist);
				 
			} catch (IOException e) {
				e.printStackTrace();
			}
			s.play(n);
		 } else {
			 logger.info("设备不在线");
		 }
	 }
    
    private List<Byte> getFileInfo(String url) throws IOException {
		 List<Byte> bytes = new ArrayList<>();
		 byte[] f = InputStream2ByteArray(url);
		 for(byte y : f) {
			 if(y == 170 || y == -86) {
				 bytes.add((byte)0xEE);
				 bytes.add((byte)0x0A);
			 } else if(y == 204 || y == -52) {
				 bytes.add((byte)0xEE);
				 bytes.add((byte)0x0C);
			 } else if(y == 238 || y == -18) {
				 bytes.add((byte)0xEE);
				 bytes.add((byte)0x0E);
			 } else {
				 bytes.add(y);
			 }
		 }
		 return bytes;
	}
   
   private byte[] InputStream2ByteArray(String filePath) throws IOException {
		InputStream in = new FileInputStream(filePath);
		byte[] data = toByteArray(in);
		in.close();
		return data;
	}
		 
	private byte[] toByteArray(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}
	
	
	
	
	//----------------------------------以下为互通平台上传数据执行的方法------------------------------------------------------------------------------------
	
	//剩余停车位上传数据
	public void sendLeftPlotList() {
		Tip tip = HikUtils.getParkingInfos(1, 400);
		if(tip.getSuccess()) {
			List<ParkDepotInfo> list = JSON.parseArray(JSONArray.toJSONString(tip.getData()), ParkDepotInfo.class);
	                                                                                                                                                                                                                                                                                            		for(ParkDepotInfo p : list) {
                ParkDepot pd = parkDepotService.findByHikId(p.getParkCode());
                if(pd != null && pd.getAiparkStatus() == 1) {
                	sendSingleLeftPlot(p, pd);
                }
            }
		}
	}
	
	public void sendSingleLeftPlot(ParkDepotInfo p, ParkDepot pd) {
		String num = UUIDFactory.get36Id();
		Map<String, String> map = new HashMap<>();
		map.put("accessKey", AiparkConfig.accessKey);
		map.put("parkCode", pd.getAiparkCode());
		map.put("timestamp", String.valueOf(System.currentTimeMillis()));
		map.put("oprNum", num);
		map.put("emptyNum", String.valueOf(p.getLeftPlot()));
		String signature = SingUtils.sing(map, AiparkConfig.accessSecret);
		map.put("signature", signature);
		NameValuePair[] data = {
				new NameValuePair("accessKey", map.get("accessKey")),
				new NameValuePair("parkCode", map.get("parkCode")),
				new NameValuePair("timestamp", map.get("timestamp")),
				new NameValuePair("oprNum", map.get("oprNum")),
				new NameValuePair("emptyNum", map.get("emptyNum")),
				new NameValuePair("signature", map.get("signature"))
		};
		try {
			String rs = HttpUtils.doPost(AiparkConfig.syncSpaceUrl, data);
			AiparkReceive h = JSONObject.parseObject(rs, AiparkReceive.class);
			if(!"0".equals(h.getState())) {
				logger.info(p.getParkName() + "上传空余车位返回结果为：" + rs);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Tip sendRecord() {

//		long begin = System.currentTimeMillis();
		Integer a = 0, b = 0;
		//查询一分钟前的出车记录
		Tip tip = HikUtils.getVehicleRecords(1, 400, "", "", "", System.currentTimeMillis() - 60000, System.currentTimeMillis(), null, 1);
		if(tip.getSuccess()) {
			HikPage hp = JSONObject.parseObject(String.valueOf(tip.getData()), HikPage.class);
			//出车记录字符串转list集合
			List<VehicleRecord> list = JSON.parseArray(JSONArray.toJSONString(hp.getList()),VehicleRecord.class);
			logger.info("查询到出车记录：" + list.size() + "条");
			//遍历出车记录
			for (int i = 0 ; i < list.size() ; i += 2) {
				ParkDepot pd = parkDepotService.findByHikId(list.get(i).getParkCode());
				//判断停车场是否存在		判断该停车场是否已上传互通平台
				if(pd != null && pd.getAiparkStatus() == 1) {
					//根据车牌号码与停车场编号查询该车的入场记录
					Tip t = HikUtils.getVehicleRecords(1, 400, pd.getHikId(), "", list.get(i).getPlateNo(), null, null, null, 0);
//					logger.info("第" + i + "条出车查询到入场状态为：" + t.getSuccess());
					if(t.getSuccess()) {
						HikPage h = JSONObject.parseObject(String.valueOf(t.getData()), HikPage.class);
						List<VehicleRecord> l = JSON.parseArray(JSONArray.toJSONString(h.getList()),VehicleRecord.class);
						//判断是否有入场记录
						if(l.size() > 0) {
							String n = UUIDFactory.get32Id();
							//虽然接口文档未做说明，但是根据查询出的多次结果来判断记录是按照时间倒序排列的。
							//上传入场记录
							AiparkReceive ar = sendSingleEntry(pd, l.get(0), n);
							//上传入场记录成功
							if("0".equals(ar.getState())) {
								//入场记录计数+1
								a ++;
								//上传出场记录
								AiparkReceive s = sendSingleExit(pd, list.get(i), l.get(0), n);
								//上传出场记录成功
								if("0".equals(s.getState())) {
									//出场记录计数+1
									b ++;
								} else {
									logger.info("出场记录上传异常：" + s.toString());
								}
							} else if("26".equals(ar.getState())) {//该入场记录已经上传过，根据返回的入场记录编号上传出场记录
								logger.info("入场记录已经上传，返回的编号为：" + ar.getDesc());
								AiparkReceive s = sendSingleExit(pd, list.get(i), l.get(0), ar.getDesc());
								if("0".equals(s.getState())) {
									b ++;
								} else {
									logger.info("出场记录上传异常：" + s.toString());
								}
							} else {//上传入场记录为止错误，则不上传出场记录
								logger.info("入场记录上传异常：" + ar.toString());
							}

						}
					}
				}
			}
		}
//		long end = System.currentTimeMillis();
//
//		long time = end - begin;
//
//		logger.info("查询耗时：" + TimeUtils.formatTime(time));
		logger.info("入场记录上传成功" + a + "条；出场记录上传成功" + b + "条");
		return tip;
	}


	public AiparkReceive sendSingleEntry(ParkDepot pd, VehicleRecord v, String rn) {
		String url = "https://www.yhxiadu.com/app/parkDepot/checkParkPicture?unid=" + v.getUnid() + "&code=" + v.getParkCode();
		logger.info(url);
		String num = UUIDFactory.get36Id();
		Map<String, String> map = new HashMap<>();
		map.put("accessKey", AiparkConfig.accessKey);
		map.put("plateNumber", v.getPlateNo());
		map.put("plateColor", String.valueOf(v.getPlateColor()));
		map.put("parkCode", pd.getAiparkCode());
		map.put("berthNumber", String.valueOf(v.getBerthCode()));
		map.put("carType", String.valueOf(v.getCarType()));
		map.put("entryTime", String.valueOf(TimeUtils.getDateByStringNoException(v.getPassTime()).getTime()));
		map.put("timestamp", String.valueOf(System.currentTimeMillis()));
		map.put("recordCode", rn);
		map.put("oprNum", num);
		map.put("entryPlatePic", url);
		map.put("entryFeaturePic", url);
		map.put("tenantCode", AiparkConfig.tenantCode);
		String signature = SingUtils.sing(map, AiparkConfig.accessSecret);
		map.put("signature", signature);
		NameValuePair[] data = {
				new NameValuePair("accessKey", map.get("accessKey")),
				new NameValuePair("plateNumber", map.get("plateNumber")),
				new NameValuePair("plateColor", map.get("plateColor")),
				new NameValuePair("parkCode", map.get("parkCode")),
				new NameValuePair("berthNumber", map.get("berthNumber")),
				new NameValuePair("carType", map.get("carType")),
				new NameValuePair("entryTime", map.get("entryTime")),
				new NameValuePair("timestamp", map.get("timestamp")),
				new NameValuePair("recordCode", map.get("recordCode")),
				new NameValuePair("oprNum", map.get("oprNum")),
				new NameValuePair("entryPlatePic", map.get("entryPlatePic")),
				new NameValuePair("entryFeaturePic", map.get("entryFeaturePic")),
				new NameValuePair("signature", map.get("signature")),
				new NameValuePair("tenantCode", map.get("tenantCode"))
		};
		AiparkReceive h = null;
		try {
			String rs = HttpUtils.doPost(AiparkConfig.syncEntryUrl, data);
			h = JSONObject.parseObject(rs, AiparkReceive.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return h;
	}

	public AiparkReceive sendSingleExit(ParkDepot pd, VehicleRecord v, VehicleRecord vr, String rn) {
		String url = "https://www.yhxiadu.com/app/parkDepot/checkParkPicture?unid=" + v.getUnid() + "&code=" + v.getParkCode();
		String num = UUIDFactory.get36Id();
		Map<String, String> map = new HashMap<>();
		map.put("accessKey", AiparkConfig.accessKey);
		map.put("plateNumber", v.getPlateNo());
		map.put("plateColor", String.valueOf(v.getPlateColor()));
		map.put("parkCode", pd.getAiparkCode());
		map.put("berthNumber", String.valueOf(v.getBerthCode()));
		map.put("carType", String.valueOf(v.getCarType()));

		map.put("entryTime", String.valueOf(TimeUtils.getDateByStringNoException(vr.getPassTime()).getTime()));
		map.put("exitTime", String.valueOf(TimeUtils.getDateByStringNoException(v.getPassTime()).getTime()));
		map.put("agioMoney", "0.00");
		map.put("shouldPay", "0.00");
		map.put("actualPay", "0.00");
		map.put("recordType", "0");
		map.put("timestamp", String.valueOf(System.currentTimeMillis()));
		map.put("recordCode", rn);
		map.put("oprNum", num);
		map.put("exitPlatePic", url);
		map.put("exitFeaturePic", url);
		map.put("tenantCode", AiparkConfig.tenantCode);
		String signature = SingUtils.sing(map, AiparkConfig.accessSecret);
		map.put("signature", signature);
		NameValuePair[] data = {
				new NameValuePair("accessKey", map.get("accessKey")),
				new NameValuePair("plateNumber", map.get("plateNumber")),
				new NameValuePair("plateColor", map.get("plateColor")),
				new NameValuePair("parkCode", map.get("parkCode")),
				new NameValuePair("berthNumber", map.get("berthNumber")),
				new NameValuePair("carType", map.get("carType")),
				new NameValuePair("entryTime", map.get("entryTime")),
				new NameValuePair("exitTime", map.get("exitTime")),
				new NameValuePair("agioMoney", map.get("agioMoney")),
				new NameValuePair("shouldPay", map.get("shouldPay")),
				new NameValuePair("actualPay", map.get("actualPay")),
				new NameValuePair("recordType", map.get("recordType")),
				new NameValuePair("timestamp", map.get("timestamp")),
				new NameValuePair("recordCode", map.get("recordCode")),
				new NameValuePair("oprNum", map.get("oprNum")),
				new NameValuePair("exitPlatePic", map.get("exitPlatePic")),
				new NameValuePair("exitFeaturePic", map.get("exitFeaturePic")),
				new NameValuePair("signature", map.get("signature")),
				new NameValuePair("tenantCode", map.get("tenantCode"))
		};
		AiparkReceive ar = null;
		try {
			String rs = HttpUtils.doPost(AiparkConfig.syncExitUrl, data);
			ar = JSONObject.parseObject(rs, AiparkReceive.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ar;
	}

	//--------------------------------------以下为修改海康账单状态的工具类-----------------------------------------------------------------------------
	private void editHikBill(Integer day, Integer hour) {
		long start = System.currentTimeMillis();
		HikBill hikBill = new HikBill();
		hikBill.setPayStatus(0);
		Date createTime;
		if(day != null) {
			createTime = TimeUtils.getWantedDateWithoutOmit(day);
		} else if(hour != null) {
			createTime = TimeUtils.getWantedHourWithoutOmit(hour);
		} else {
			createTime = TimeUtils.getWantedDateWithoutOmit(-1000);
		}
		hikBill.setCreateTime(createTime);
		List<HikBill> list = hikBillService.findByPayStatus(hikBill);
		logger.info("查询到的未支付的数据为" + list.size() + "条");
		int a = 0, b = 0, c = 0;
		for(HikBill hb : list) {
			List<ChargeRecord> crs = HikUtils.getChargeByPlateNo(hb.getCreateTime().getTime() - 864000000, hb.getCreateTime().getTime(), hb.getParkCode(), hb.getPlateNo(), hb.getPlateColor());
			for(ChargeRecord cr : crs) {
				c ++;
				if(hb.getInTime().longValue() == cr.getInTime().longValue()) {
					hb.setUpdateTime(new Date());
					hb.setPayStatus(1);
					hb.setPayMethod(0);
					try {
						hikBillService.updateById(hb);
						a ++;
					} catch (Exception e) {
						e.printStackTrace();
						b ++;
					}
					break;
				}
			}
		}
		long end = System.currentTimeMillis();
		logger.info("修改账单耗时：" + TimeUtils.formatTime(end - start) + "；可被修改：" + c + "条；修改成功：" + a + "条；修改失败：" + b + "条");
	}


	private void handleScreenWord(GuideScreen gs) {
		boolean clean;
		String url = "/images/guide-screen/download-method/", fileName, imageName;
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext.getServletContext();
		String filePath = servletContext.getRealPath(url);
		//当前已经是第一张图片
		if(gs.getPlayNumber() == 1) {
			clean = false;
			gs.setPlayNumber(2);
			fileName = "play002.lst";
			imageName = "zhihuitingche.jpg";
		} else {//当前不是第一张图片
			clean = true;
			gs.setPlayNumber(1);
			fileName = "play001.lst";
			imageName = "chuesaohei.jpg";
		}
		gs.setUpdateTime(new Date());
		gs.setPlayFileUrl(url);
		gs.setPlayFileName(fileName);
		gs.setImageName(imageName);
		try {
			gss.updateById(gs);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("修改类型失败");
		}
		sendToScreen(gs.getPlayNumber(), gs.getNumber(), filePath, fileName, imageName, clean);
	}

	public Tip handleScreenWord2(GuideScreen gs) {
		boolean clean;
		String url = "/images/guide-screen/download-method/", fileName, imageName;
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext.getServletContext();
		String filePath = servletContext.getRealPath(url);
		//当前已经是第一张图片
		clean = false;
		gs.setPlayNumber(2);
		fileName = "play001.lst";
		imageName = "chuesaohei.jpg";
		gs.setUpdateTime(new Date());
		gs.setPlayFileUrl(url);
		gs.setPlayFileName(fileName);
		gs.setImageName(imageName);
		try {
			gss.updateById(gs);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("修改类型失败");
		}
		sendToScreen(gs.getPlayNumber(), gs.getNumber(), filePath, fileName, imageName, clean);
		return new Tip();
	}
	
}
